<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增微信通知' : '编辑微信通知'"
    :visible.sync="visible"
    width="600px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="110px" style="margin: 0 50px;">
      <el-form-item label="接收人:" prop="userName">
        <el-input v-model="temp.userName" disabled>
          <el-button v-if="type === 'add'" slot="append" class="append-search" @click="openUserList">获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="openId:" prop="openId">
        <el-input v-model="temp.openId" disabled />
      </el-form-item>
      <el-form-item label="接收范围:" prop="orgId" class="block">
        <el-tree-select
          v-model="temp.orgId"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="时间" prop="date">
        <el-date-picker
          v-model="temp.date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="通知内容类型" prop="checkType">
        <el-checkbox-group v-model="temp.checkType">
          <el-checkbox :label="1">特价一级审批</el-checkbox>
          <el-checkbox :label="2">特价二级审批</el-checkbox>
          <el-checkbox :label="4">退单审批</el-checkbox>
          <el-checkbox :label="8">退款审批</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" prop="noticeStatus">
        <el-select v-model="temp.noticeStatus">
          <el-option :value="2" label="启用" />
          <el-option :value="1" label="停用" />
          <el-option :value="-1" label="作废" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
    <user-list ref="user" :tree-data="treeData" />
  </el-dialog>
</template>

<script>
  import { wechatBusinessNoticeAdd } from '@/api'
  import UserList from './UserList'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'

  export default {
    name: 'add',
    components: {
      UserList
    },
    data() {
      return {
        visible: false,
        type: 'add',
        treeData: [],
        currentUser: null,
        temp: {
          userName: '',
          orgId: '',
          date: '',
          checkType: [],
          noticeStatus: 2
        },
        rules: {
          userName: [{ required: true, message: '请选择接收用户', trigger: 'change' }],
          orgId: [{ required: true, message: '请请选择生效范围', trigger: 'change' }],
          openId: [{ required: true, message: 'openId不能为空', trigger: 'change' }],
          date: [{ required: true, message: '请选择时间', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    created() {
      this.getTreeData()
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              orgId: temp.scopeOrgId,
              checkType: [1, 2, 4, 8].filter(item => item & temp.roleOption),
              date: [moment(temp.startDt), moment(temp.endDt)]
            })
            this.type = 'edit'
          }
        })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 点击接收人
      async openUserList() {
        const res = await this.$refs.user.open()
        this.currentUser = res
        this.$set(this.temp, 'userName', res.userName)
        this.$set(this.temp, 'openId', res.openId)
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const org = this.orgList.find(item => item.orgId === this.temp.orgId)
          const params = {
            userName: this.temp.userName,
            userId: this.currentUser ? this.currentUser.userId : this.temp.userId,
            userCode: this.currentUser ? this.currentUser.userCode : this.temp.userCode,
            openId: this.temp.openId,
            scopeOrgId: org.orgId,
            scopeOrgSNNo: org.orgSNNo,
            scopeOrgName: org.orgName,
            noticeStatus: this.temp.noticeStatus,
            startDt: moment(this.temp.date[0]).format(),
            endDt: moment(this.temp.date[1]).format()
          }
          let type = 0
          this.temp.checkType.forEach(item => {
            type |= item
          })
          params.roleOption = type
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await wechatBusinessNoticeAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await wechatBusinessNoticeAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          userName: '',
          orgId: '',
          date: '',
          checkType: [],
          noticeStatus: 2
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
